﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace LinqToDB.Provider
{
    /// <summary>
    /// 数据表
    /// </summary>
    /// <typeparam name="T">表元素类型</typeparam>
    public class Table<T> : ITable, IQueryable<T>, IQueryable, IQueryProvider
    {
        /// <summary>
        /// 数据源
        /// </summary>
        SqlProvider m_provider;

        /// <summary>
        /// 构造表
        /// </summary>
        public Table()
        {
            m_provider = new SqlProvider();
        }

        /// <summary>
        /// 表名
        /// </summary>
        public string TableName
        {
            get { return typeof(T).Name; }
        }

        #region 查询接口实现
        /// <summary>
        /// 元素类型
        /// </summary>
        Type IQueryable.ElementType
        {
            get { return typeof(T); }
        }
        /// <summary>
        /// 表的查询表达式
        /// </summary>
        Expression IQueryable.Expression
        {
            get { return Expression.Constant(this); }
        }
        /// <summary>
        /// 数据源
        /// </summary>
        IQueryProvider IQueryable.Provider
        {
            get { return this; }
        }

        IQueryable<TElement> IQueryProvider.CreateQuery<TElement>(System.Linq.Expressions.Expression expression)
        {
            return new DataQuery<TElement>(this.m_provider, expression);
        }

        IQueryable IQueryProvider.CreateQuery(System.Linq.Expressions.Expression expression)
        {
            return (IQueryable)Activator.CreateInstance(typeof(DataQuery<>).MakeGenericType(expression.Type)
                , this.m_provider, expression);
        }

        TResult IQueryProvider.Execute<TResult>(System.Linq.Expressions.Expression expression)
        {
            return (TResult)this.m_provider.Execute(expression);
        }

        object IQueryProvider.Execute(System.Linq.Expressions.Expression expression)
        {
            return this.m_provider.Execute(expression);
        }


        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            throw new NotImplementedException();
        }


        IEnumerator<T> IEnumerable<T>.GetEnumerator()
        {
            return (IEnumerator<T>)m_provider.Execute(((IQueryable)this).Expression);
        }
        #endregion
    }
}
